package com.huibei.wateradmin.authority.service;

import com.huibei.wateradmin.authority.domain.Role;
import com.huibei.wateradmin.authority.domain.User;
import com.huibei.wateradmin.authority.exception.ToClientException;
import com.huibei.wateradmin.authority.message.ClientUserInfo;
import com.huibei.wateradmin.authority.repository.UserRepository;
import com.huibei.wateradmin.authority.util.Err;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * Created by wanglinlin on 2016/7/16.
 */
@Service
@Transactional
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public void create(String email, String password, String cnName) {
        User user = userRepository.findByEmail(email);
        if (user != null) {
            throw new ToClientException(Err.user_already_register);
        }
        user = new User(email,cnName,password);
        Role role = new Role();
        role.setId(1L);
        user.setRole(role);
        userRepository.save(user);
    }

    public Page<ClientUserInfo> findByPage(PageRequest request) {
        Page<User> page = userRepository.findAll(request);
        return page.map(ClientUserInfo::convertToClient);
    }

    public ClientUserInfo findClientInfoById(Long id) {
        User user = userRepository.findOne(id);
        if (user == null) {
            return new ClientUserInfo();
        }
        return ClientUserInfo.convertToClient(user);
    }

    public void updateUser(Long id, Long roleId, String cnName) {
        User user;
        if (id == null) {
            user = new User();
            user.setIsValid(true);
        }else {
            user = userRepository.getOne(id);
        }
        user.setCnName(cnName);
        Role role = new Role();
        role.setId(roleId);
        user.setRole(role);
        userRepository.save(user);
    }

    public User checkLogin(String email, String password) {
        return userRepository.findByEmailAndPassword(email,password);
    }

    public User findById(Long userId) {
        return userRepository.findOne(userId);
    }
}
